/*! \file togglebtn.cpp	
	
	This contains the implementation of the ButtonGroup and ToggleButton classes
*/

#include "togglebtn.h"
#include "guiclass.h"
#include "image.h"
#include <GL\glfw.h>


ToggleButton::ToggleButton( Component* parent, int imageID, int depressedImageID ) :
	ImageButton( parent, imageID, depressedImageID ),
	selected( false ),
	group( 0 )
{
	
	
}


void ToggleButton::setSelected( bool selected ) {
	this->selected = selected;
	if ( selected && group != 0 ) {
		group->select( this );
	}
}

void ToggleButton::toggle() {
	setSelected( !selected );
}

bool ToggleButton::getSelected() {
	return selected;
}

void ToggleButton::setGroup( ButtonGroup* g ) {
	group = g;
}

void ToggleButton::mouseDown( Event e ) {
	//~ if ( group == 0 ) {
		//~ toggle();
	//~ } else {
		//~ setSelected();
	//~ }
}

void ToggleButton::performAction() {
	Button::performAction(); // alert listeners
	if ( group == 0 ) {
		toggle();
	} else {
		setSelected();
	}
}

void ToggleButton::keyDown( Event e ) {
	if ( e.button == GLFW_KEY_ENTER || e.button == GLFW_KEY_SPACE ) {
		if ( group == 0 ) {
			toggle();
		} else {
			setSelected();
		}
	}
}

void ToggleButton::draw() {
	int imageToUse = image;
	if ( selected ) {
		imageToUse = depressedImage;
	}
	
	int textureID = ImageHandler::getInstance()->getWorkingTexture();
	if ( stretchOnResize ) {
		ImageHandler::getInstance()->blit( textureID, imageToUse, 9999.0f, w, h );
	} else {
		ImageHandler::getInstance()->blit( textureID, imageToUse );
	}	
	
}
ButtonGroup::ButtonGroup( Component* parent ) :
	Component( parent ),
	selected(0)
{
	
	
}

void ButtonGroup::add( ToggleButton* b ) {
	list<ToggleButton*>::iterator i;
	for ( i = buttons.begin(); i != buttons.end(); ++i ) {
		// already in this
		if ( (*i) == b ) {
			return;
		}
	}
	b->setGroup( this );
	buttons.push_back( b );
}
void ButtonGroup::select( ToggleButton* b ) {
	list<ToggleButton*>::iterator i;
	for ( i = buttons.begin(); i != buttons.end(); ++i ) {
		if ( (*i) == b ) {
			// don't actually setSelected( true ) here because it was already done and it will make an infinite loop
			selected = (*i);
		} else {
			(*i)->setSelected( false );
		}
	}
}
